<template>
  <div>
    <h2 style="text-align: center;">发布新课程</h2>

    <el-steps :active="1" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息" />
      <el-step title="创建课程大纲" />
      <el-step title="最终发布" />
    </el-steps>

    <el-form label-width="120px">
      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写" />
      </el-form-item>

      <el-form-item label="课程分类">
        <el-select
          v-model="courseInfo.subjectId"
          placeholder="一级分类"
          @change="subjectLevelOneChanged"
        >
          <el-option
            v-for="subjectOne in subjectOneList"
            :key="subjectOne.id"
            :label="subjectOne.title"
            :value="subjectOne.id"
          />
        </el-select>
        <el-select v-model="courseInfo.subjectParentId" placeholder="二级分类">
          <el-option
            v-for="subjectTwo in subjectTwoList"
            :key="subjectTwo.id"
            :label="subjectTwo.title"
            :value="subjectTwo.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number
          :min="0"
          v-model="courseInfo.lessonNum"
          controls-position="right"
          placeholder="请填写课程的总课时数"
        />
      </el-form-item>

      <!-- 课程简介，使用富文本编辑器，可以上传图片、文字等，图片和文字默认存储在数据库中，而不是Oss
            Tinymce中的图片上传功能直接存储的是图片的base64编码，使用的数据库数据类型是text
      而文字样式也会存储到数据库中-->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description" />
      </el-form-item>

      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API+'/eduoss/ossfile/upload'"
          class="avatar-uploader"
        >
          <img :src="courseInfo.cover" />
        </el-upload>
      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number
          :min="0"
          v-model="courseInfo.price"
          controls-position="right"
          placeholder="免费课程请设置为0元"
        />元
      </el-form-item>
      <!-- element-ui官网是每次点击下一步是active+1,而本页面是使用路由跳转 -->
      <!-- <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存并下一步</el-button>
      </el-form-item>-->
      <div>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存并下一步</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import CourseApi from "@/api/edu/course";
import SubjectApi from "@/api/edu/subject";
//富文本编辑器
import Tinymce from "@/components/Tinymce";
export default {
  components: { Tinymce },
  props: {},
  data() {
    return {
      saveBtnDisabled: false, // 保存按钮是否禁用
      courseInfo: {
        title: "",
        subjectId: "", //一级课程分类id
        subjectParentId: "", //二级课程分类id
        teacherId: "",
        lessonNum: 0,
        description: "",
        cover: "/static/cover.jpg", //封面
        price: 0
      },
      courseId: "",
      BASE_API: process.env.BASE_API, // 接口API地址
      teacherList: [], //讲师列表
      subjectOneList: [], //一级课程分类列表
      subjectTwoList: [] //二级课程分类列表
    };
  },
  watch: {
    //路由监听
    $route(to, from) {
      //路由一发生变化，就执行下面的操作
      this.init();
    }
  },
  computed: {},
  methods: {
    //数据初始化
    init() {
      if (this.$route.params && this.$route.params.id) {
      } else {
        //添加数据时，清空之前的数据
        this.courseInfo = {
          //默认封面
          cover: "/static/cover.jpg",
          lessonNum: 0,
          price: 0
        };
      }
    },
    //封面上传成功调用的方法
    handleAvatarSuccess(res, file) {
      //res就表示后端响应的结果
      this.courseInfo.cover = res.data.url;
    },
    //封面上传前调用的方法，一般由于校验文件格式和文件大小，返回值是true则表示可以上传
    beforeAvatarUpload(file) {
      //file代表要上传的文件
      const isJPG = file.type === "image/jpeg";
      //上传文件不得大于2M
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //保存数据
    saveInfo() {
      CourseApi.saveCourseInfo(this.courseInfo).then(res => {
        //提示
        this.$message({
          type: "success",
          message: "课程信息保存成功"
        });
        //跳转到课程大纲页，并携带课程id，因为课程大纲表需要存储课程id
        this.$router.push({ path: "/course/chapter/" + res.data.courseId });
      });
    },
    //修改数据
    updateInfo() {
      CourseApi.updateCourseInfo(this.courseInfo).then(res => {
        //提示
        this.$message({
          type: "success",
          message: "课程信息修改成功"
        });
        this.$router.push({ path: "/course/chapter/" + this.courseId });
      });
    },
    //根据课程id是否存在决定是保存操作还是新增操作】
    saveOrUpdate() {
      if (!this.courseInfo.id) {
        this.saveInfo();
      } else {
        this.updateInfo();
      }
    },
    //获取讲师列表
    getTeacherList() {
      CourseApi.getTeacherList().then(res => {
        this.teacherList = res.data.list;
      });
    },
    //获取课程一级分类
    getSubjectOneList() {
      SubjectApi.getSubjectList().then(res => {
        this.subjectOneList = res.data.list;
      });
    },
    //一级分类选中改变时触发
    subjectLevelOneChanged(subjectOneId) {
      //遍历一级分类，获取与选中的一级分类id相同的一级分类
      for (var i = 0; i < this.subjectOneList.length; i++) {
        if (subjectOneId === this.subjectOneList[i].id) {
          //将一级分类的二级分类列表赋给二级分类
          this.subjectTwoList = this.subjectOneList[i].children;
          //课程分类改变时，清除二级分类的id
          this.courseInfo.subjectParentId = "";
        }
      }
    },
    //获取课程基本信息
    getCourseInfo() {
      CourseApi.getCourseInfo(this.courseId).then(res => {
        this.courseInfo = res.data.info;
        SubjectApi.getSubjectList().then(result => {
          //获取分类列表
          this.subjectOneList = result.data.list;
          //遍历分类列表，获取指定的二级分类，实现修改课程信息时二级分类回显
          for (var i = 0; i < this.subjectOneList.length; i++) {
            if (this.courseInfo.subjectId == this.subjectOneList[i].id) {
              this.subjectTwoList = this.subjectOneList[i].children;
            }
          }
        });
      });
    }
  },
  created() {
    if (this.$route.params && this.$route.params.id) {
      //修改课程信息的操作
      this.courseId = this.$route.params.id;
      this.getCourseInfo();
    } else {
      //添加课程信息的操作
      this.getSubjectOneList();
    }
    //共同操作
    this.getTeacherList();
  },
  mounted() {}
};
</script>
<style scoped>
/* scoped代表样式只在该页面生效 */
.tinymce-container {
  line-height: 29px;
}
</style>